import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Modal, Form, Input, Select, InputNumber, Upload, message, Row, Col, Tag, Image, Typography, Tooltip, Badge, Dropdown, Menu as AntMenu, Switch, DatePicker, Statistic } from 'antd';
import { MENU_COLUMNS } from '../shared/table/columns';
import BaseTable from '../shared/table/BaseTable';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, UploadOutlined, SearchOutlined, FilterOutlined, MoreOutlined, ShoppingOutlined, DollarOutlined, StarOutlined, FireOutlined, ReloadOutlined, ExportOutlined, ImportOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { getErrorMessage, getSuccessMessage, getHttpErrorMessage, PAGES, ERROR_TYPES, SUCCESS_TYPES } from '../utils/i18n';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

const MenuPage = () => {
  const [menuItems, setMenuItems] = useState([
    {
      id: 1,
      name: '经典汉堡',
      category: '主食',
      price: 28.50,
      originalPrice: 32.00,
      description: '新鲜牛肉饼配生菜、番茄、洋葱',
      image: null,
      status: 'available',
      isHot: true,
      isNew: false,
      stock: 50,
      sales: 156,
      rating: 4.8,
      createTime: '2024-01-10 10:30:00',
      updateTime: '2024-01-15 14:20:00'
    },
    {
      id: 2,
      name: '香辣鸡腿堡',
      category: '主食',
      price: 32.00,
      originalPrice: 35.00,
      description: '香辣鸡腿配特制酱料',
      image: null,
      status: 'available',
      isHot: false,
      isNew: true,
      stock: 30,
      sales: 89,
      rating: 4.6,
      createTime: '2024-01-12 15:45:00',
      updateTime: '2024-01-15 16:10:00'
    },
    {
      id: 3,
      name: '可乐',
      category: '饮品',
      price: 8.00,
      originalPrice: 10.00,
      description: '冰镇可口可乐',
      image: null,
      status: 'available',
      isHot: false,
      isNew: false,
      stock: 100,
      sales: 234,
      rating: 4.5,
      createTime: '2024-01-08 09:15:00',
      updateTime: '2024-01-14 11:30:00'
    },
    {
      id: 4,
      name: '薯条',
      category: '小食',
      price: 12.00,
      originalPrice: 15.00,
      description: '金黄酥脆薯条',
      image: null,
      status: 'unavailable',
      isHot: true,
      isNew: false,
      stock: 0,
      sales: 178,
      rating: 4.7,
      createTime: '2024-01-05 14:20:00',
      updateTime: '2024-01-15 10:45:00'
    },
    {
      id: 5,
      name: '巧克力蛋糕',
      category: '甜品',
      price: 25.00,
      originalPrice: 28.00,
      description: '浓郁巧克力蛋糕',
      image: null,
      status: 'available',
      isHot: false,
      isNew: true,
      stock: 20,
      sales: 45,
      rating: 4.9,
      createTime: '2024-01-14 16:30:00',
      updateTime: '2024-01-15 12:15:00'
    }
  ]);

  const [categories] = useState([
    { value: '主食', label: '主食', color: '#1890ff' },
    { value: '饮品', label: '饮品', color: '#52c41a' },
    { value: '小食', label: '小食', color: '#faad14' },
    { value: '甜品', label: '甜品', color: '#f5222d' },
    { value: '其他', label: '其他', color: '#722ed1' }
  ]);

  const [loading, setLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [importLoading, setImportLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingItem, setEditingItem] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [dateRange, setDateRange] = useState(null);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [stats, setStats] = useState({
    totalItems: 0,
    availableItems: 0,
    hotItems: 0,
    totalSales: 0
  });

  // 计算过滤后的数据
  const filteredData = menuItems.filter(item => {
    // 搜索文本过滤
    if (searchText && !item.name.toLowerCase().includes(searchText.toLowerCase()) && 
        !item.description.toLowerCase().includes(searchText.toLowerCase())) {
      return false;
    }
    
    // 分类过滤
    if (categoryFilter !== 'all' && item.category !== categoryFilter) {
      return false;
    }
    
    // 状态过滤
    if (statusFilter !== 'all' && item.status !== statusFilter) {
      return false;
    }
    
    // 日期范围过滤
    if (dateRange && dateRange.length === 2) {
      const itemDate = dayjs(item.createTime);
      if (itemDate.isBefore(dateRange[0]) || itemDate.isAfter(dateRange[1])) {
        return false;
      }
    }
    
    return true;
  });

  useEffect(() => {
    calculateStats();
  }, [menuItems]);

  const calculateStats = () => {
    const totalItems = menuItems.length;
    const availableItems = menuItems.filter(item => item.status === 'available').length;
    const hotItems = menuItems.filter(item => item.isHot).length;
    const totalSales = menuItems.reduce((sum, item) => sum + item.sales, 0);

    setStats({
      totalItems,
      availableItems,
      hotItems,
      totalSales
    });
  };

  const getStatusColor = (status) => {
    const colors = {
      available: 'success',
      unavailable: 'error',
      hidden: 'warning'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status) => {
    const texts = {
      available: '可售',
      unavailable: '缺货',
      hidden: '隐藏'
    };
    return texts[status] || status;
  };

  const getCategoryColor = (category) => {
    const categoryObj = categories.find(cat => cat.value === category);
    return categoryObj ? categoryObj.color : '#666';
  };

  const handleEdit = (item) => {
    setEditingItem(item);
    form.setFieldsValue({
      name: item.name,
      category: item.category,
      price: item.price,
      originalPrice: item.originalPrice,
      description: item.description,
      status: item.status,
      isHot: item.isHot,
      isNew: item.isNew,
      stock: item.stock
    });
    setModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个菜品吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setMenuItems(menuItems.filter(item => item.id !== id));
        message.success('删除成功');
      }
    });
  };

  const handleExport = async () => {
    try {
      setExportLoading(true);
      // 模拟导出功能
      const csvContent = "data:text/csv;charset=utf-8," + 
        "菜品名称,分类,价格,原价,状态,库存,销量,评分,创建时间\n" +
        filteredMenuItems.map(item => 
          `${item.name},${item.category},${item.price},${item.originalPrice},${item.status === 'available' ? '可售' : '不可售'},${item.stock},${item.sales},${item.rating},${item.createTime}`
        ).join("\n");
      
      const encodedUri = encodeURI(csvContent);
      const link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", `菜品列表_${dayjs().format('YYYY-MM-DD')}.csv`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    } finally {
      setExportLoading(false);
    }
  };

  const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.csv,.xlsx';
    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;
      
      try {
        setImportLoading(true);
        // 这里应该实现文件解析和数据导入逻辑
        // 目前只是模拟
        await new Promise(resolve => setTimeout(resolve, 2000));
        message.success('导入成功');
      } catch (error) {
        message.error('导入失败');
      } finally {
        setImportLoading(false);
      }
    };
    input.click();
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      if (editingItem) {
        // 编辑菜品
        setMenuItems(menuItems.map(item => 
          item.id === editingItem.id 
            ? { 
                ...item, 
                ...values, 
                updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
              }
            : item
        ));
        message.success('菜品信息更新成功');
      } else {
        // 新增菜品
        const newItem = {
          id: Date.now(),
          ...values,
          image: null,
          sales: 0,
          rating: 0,
          createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        };
        setMenuItems([...menuItems, newItem]);
        message.success('菜品添加成功');
      }
      
      setModalVisible(false);
      setEditingItem(null);
      form.resetFields();
    } catch (error) {
      console.error('保存失败:', error);
      message.error(getErrorMessage(PAGES.MENU, ERROR_TYPES.SAVE_FAILED));
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = (itemId, newStatus) => {
    setMenuItems(menuItems.map(item => 
      item.id === itemId 
        ? { 
            ...item, 
            status: newStatus,
            updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
          }
        : item
    ));
    message.success(`菜品状态已更新为${getStatusText(newStatus)}`);
  };

  const handleToggleHot = (itemId) => {
    setMenuItems(menuItems.map(item => 
      item.id === itemId 
        ? { 
            ...item, 
            isHot: !item.isHot,
            updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
          }
        : item
    ));
    message.success('热门状态已更新');
  };

  // 快捷日期选择函数
  const handleQuickDateSelect = (days) => {
    const endDate = dayjs();
    const startDate = dayjs().subtract(days, 'day');
    setDateRange([startDate, endDate]);
  };

  const clearDateFilter = () => {
    setDateRange(null);
  };

  const filteredItems = menuItems.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         item.description.toLowerCase().includes(searchText.toLowerCase());
    const matchesCategory = categoryFilter === 'all' || item.category === categoryFilter;
    const matchesStatus = statusFilter === 'all' || item.status === statusFilter;
    
    let matchesDate = true;
    if (dateRange && dateRange.length === 2) {
      const itemDate = dayjs(item.updateTime);
      matchesDate = itemDate.isAfter(dateRange[0].startOf('day')) && itemDate.isBefore(dateRange[1].endOf('day'));
    }
    
    return matchesSearch && matchesCategory && matchesStatus && matchesDate;
  });

  const getActionMenu = (item) => (
    <AntMenu>
      <AntMenu.Item key="edit" icon={<EditOutlined />} onClick={() => handleEdit(item)}>
        编辑菜品
      </AntMenu.Item>
      <AntMenu.Item key="available" onClick={() => handleStatusChange(item.id, 'available')}>
        设为可售
      </AntMenu.Item>
      <AntMenu.Item key="unavailable" onClick={() => handleStatusChange(item.id, 'unavailable')}>
        设为缺货
      </AntMenu.Item>
      <AntMenu.Item key="hidden" onClick={() => handleStatusChange(item.id, 'hidden')}>
        隐藏菜品
      </AntMenu.Item>
      <AntMenu.Item key="hot" onClick={() => handleToggleHot(item.id)}>
        {item.isHot ? '取消热门' : '设为热门'}
      </AntMenu.Item>
      <AntMenu.Divider />
      <AntMenu.Item key="delete" icon={<DeleteOutlined />} danger onClick={() => handleDelete(item.id)}>
        删除菜品
      </AntMenu.Item>
    </AntMenu>
  );

  // 基于统一列配置生成实际渲染列
  const columns = MENU_COLUMNS.map(column => {
    if (column.key === 'image') {
      return {
        ...column,
        render: (_, item) => (
          <div style={{ position: 'relative', display: 'flex', justifyContent: 'center' }}>
            <Image
              width={48}
              height={48}
              src={item.image || '/images/menu-placeholder.svg'}
              style={{ borderRadius: '6px', objectFit: 'cover' }}
              preview={{
                visible: false,
                onVisibleChange: (visible) => {
                  if (visible) {
                    setPreviewImage(item.image || '/images/menu-placeholder.svg');
                    setPreviewVisible(true);
                  }
                }
              }}
            />
            {item.isHot && (
              <Badge 
                count={<FireOutlined style={{ color: '#f5222d', fontSize: '10px' }} />} 
                style={{ position: 'absolute', top: -2, right: -2 }}
                size="small"
              />
            )}
          </div>
        )
      };
    }
    if (column.key === 'name') {
      return {
        ...column,
        render: (name, item) => (
          <div>
            <div style={{ fontWeight: 600, fontSize: '14px', marginBottom: '2px' }}>
              {name}
            </div>
            {item.isNew && (
              <Badge count="新" size="small" style={{ backgroundColor: '#52c41a', fontSize: '10px' }} />
            )}
          </div>
        )
      };
    }
    if (column.key === 'description') {
      return {
        ...column,
        render: (description) => (
          <div style={{ 
            color: '#666', 
            fontSize: '12px',
            lineHeight: '1.4',
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
            textOverflow: 'ellipsis'
          }}>
            {description}
          </div>
        )
      };
    }
    if (column.key === 'price') {
      return {
        ...column,
        render: (_, item) => (
          <div>
            <div style={{ fontWeight: 600, color: '#f5222d', fontSize: '14px' }}>
              ¥{item.price}
            </div>
            {item.originalPrice > item.price && (
              <div style={{ color: '#999', fontSize: '11px', textDecoration: 'line-through' }}>
                ¥{item.originalPrice}
              </div>
            )}
          </div>
        )
      };
    }
    if (column.key === 'category') {
      return {
        ...column,
        render: (category) => (
          <Tag color={getCategoryColor(category)} style={{ borderRadius: '12px', fontSize: '11px' }}>
            {category}
          </Tag>
        )
      };
    }
    if (column.key === 'status') {
      return {
        ...column,
        render: (status) => (
          <Tag color={getStatusColor(status)} style={{ borderRadius: '12px', fontSize: '11px' }}>
            {getStatusText(status)}
          </Tag>
        )
      };
    }
    if (column.key === 'stock') {
      return {
        ...column,
        render: (stock) => (
          <div style={{ 
            color: stock > 10 ? '#52c41a' : stock > 0 ? '#faad14' : '#f5222d',
            fontWeight: 600,
            fontSize: '13px',
            textAlign: 'center'
          }}>
            {stock}
          </div>
        )
      };
    }
    if (column.key === 'rating') {
      return {
        ...column,
        render: (rating) => (
          <div style={{ display: 'flex', alignItems: 'center', gap: '2px', justifyContent: 'center' }}>
            <StarOutlined style={{ color: '#faad14', fontSize: '11px' }} />
            <span style={{ fontSize: '12px' }}>{rating}</span>
          </div>
        )
      };
    }
    if (column.key === 'actions') {
      return {
        ...column,
        render: (_, item) => (
          <div style={{ display: 'flex', gap: '4px', justifyContent: 'flex-end' }}>
            <Tooltip title="编辑">
              <Button 
                type="primary" 
                size="small" 
                icon={<EditOutlined />}
                onClick={() => handleEdit(item)}
              />
            </Tooltip>
            <Dropdown overlay={getActionMenu(item)} trigger={['click']}>
              <Button size="small" icon={<MoreOutlined />} />
            </Dropdown>
          </div>
        )
      };
    }
    return column;
  });

  const uploadProps = {
    name: 'image',
    action: editingItem?.id ? `/api/admin/menu/items/${editingItem.id}/image` : null,
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('token')}`,
    },
    beforeUpload: (file) => {
      // 检查文件类型
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      if (!isImage) {
        message.error('只能上传 JPEG、PNG、WebP 格式的图片!');
        return false;
      }
      // 检查文件大小 (5MB)
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过 5MB!');
        return false;
      }
      // 如果没有选择菜品，不允许上传
      if (!editingItem?.id) {
        message.error('请先保存菜品信息后再上传图片!');
        return false;
      }
      return true;
    },
    onChange(info) {
      if (info.file.status === 'uploading') {
        message.loading(`正在上传 ${info.file.name}...`, 0);
      } else if (info.file.status === 'done') {
        message.destroy();
        message.success(`${info.file.name} 上传成功!`);
        // 刷新菜品列表以显示新图片
        fetchMenuItems();
      } else if (info.file.status === 'error') {
        message.destroy();
        message.error(`${info.file.name} 上传失败: ${info.file.response?.message || '未知错误'}`);
      }
    },
    disabled: !editingItem?.id,
  };

  return (
    <div style={{ padding: '24px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      <div style={{ 
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        borderRadius: '16px',
        padding: '24px',
        marginBottom: '24px',
        boxShadow: '0 4px 20px rgba(0,0,0,0.1)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div style={{ 
            background: 'rgba(255,255,255,0.2)',
            borderRadius: '12px',
            padding: '12px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}>
            <ShoppingOutlined style={{ fontSize: '32px', color: '#fff' }} />
          </div>
          <div>
            <Title level={2} style={{ margin: 0, color: '#fff' }}>
              菜单管理
            </Title>
            <p style={{ margin: '8px 0 0 0', color: 'rgba(255,255,255,0.8)', fontSize: '16px' }}>
              管理餐厅菜品信息、价格和库存状态
            </p>
          </div>
        </div>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} lg={6}>
          <Card 
            style={{ 
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              border: 'none',
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
            }}
          >
            <Statistic
              title={<span style={{ color: '#fff', fontSize: '14px' }}>菜品总数</span>}
              value={stats.totalItems}
              prefix={<ShoppingOutlined style={{ color: '#fff', fontSize: '20px' }} />}
              valueStyle={{ color: '#fff', fontSize: '28px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card 
            style={{ 
              background: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
              border: 'none',
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
            }}
          >
            <Statistic
              title={<span style={{ color: '#fff', fontSize: '14px' }}>可售菜品</span>}
              value={stats.availableItems}
              prefix={<ShoppingOutlined style={{ color: '#fff', fontSize: '20px' }} />}
              valueStyle={{ color: '#fff', fontSize: '28px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card 
            style={{ 
              background: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
              border: 'none',
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
            }}
          >
            <Statistic
              title={<span style={{ color: '#fff', fontSize: '14px' }}>热门菜品</span>}
              value={stats.hotItems}
              prefix={<FireOutlined style={{ color: '#fff', fontSize: '20px' }} />}
              valueStyle={{ color: '#fff', fontSize: '28px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card 
            style={{ 
              background: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
              border: 'none',
              borderRadius: '12px',
              boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
            }}
          >
            <Statistic
              title={<span style={{ color: '#fff', fontSize: '14px' }}>总销量</span>}
              value={stats.totalSales}
              prefix={<DollarOutlined style={{ color: '#fff', fontSize: '20px' }} />}
              valueStyle={{ color: '#fff', fontSize: '28px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 菜品列表 */}
      <Card 
        title={<Title level={4} style={{ margin: 0, color: '#1a1a1a' }}>菜品列表</Title>}
        style={{
          borderRadius: '16px',
          boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
          border: 'none',
          overflow: 'hidden'
        }}
        extra={
          <Space>
            <Button 
              icon={<ImportOutlined />} 
              style={{ borderRadius: '8px' }}
              onClick={handleImport}
              loading={importLoading}
            >
              导入
            </Button>
            <Button 
              icon={<ExportOutlined />} 
              style={{ borderRadius: '8px' }}
              onClick={handleExport}
              loading={exportLoading}
            >
              导出
            </Button>
            <Button icon={<ReloadOutlined />} onClick={() => window.location.reload()} style={{ borderRadius: '8px' }}>刷新</Button>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingItem(null);
                form.resetFields();
                setModalVisible(true);
              }}
              style={{ 
                borderRadius: '8px',
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                border: 'none',
                boxShadow: '0 2px 8px rgba(102, 126, 234, 0.3)'
              }}
            >
              添加菜品
            </Button>
          </Space>
        }
      >
        {/* 筛选器 */}
        <div style={{ 
          marginBottom: '20px', 
          padding: '16px',
          background: '#fafafa',
          borderRadius: '12px',
          display: 'flex', 
          gap: '12px', 
          flexWrap: 'wrap',
          alignItems: 'center'
        }}>
          <Input.Search
            placeholder="搜索菜品名称或描述"
            style={{ 
              width: 300,
              borderRadius: '8px'
            }}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            prefix={<SearchOutlined />}
          />
          <Select
            placeholder="分类筛选"
            style={{ 
              width: 120,
              borderRadius: '8px'
            }}
            value={categoryFilter}
            onChange={setCategoryFilter}
          >
            <Option value="all">全部分类</Option>
            {categories.map(cat => (
              <Option key={cat.value} value={cat.value}>{cat.label}</Option>
            ))}
          </Select>
          <Select
            placeholder="状态筛选"
            style={{ 
              width: 120,
              borderRadius: '8px'
            }}
            value={statusFilter}
            onChange={setStatusFilter}
          >
            <Option value="all">全部状态</Option>
            <Option value="available">可售</Option>
            <Option value="unavailable">缺货</Option>
            <Option value="hidden">隐藏</Option>
          </Select>
        </div>
        
        {/* 日期筛选器 */}
        <div style={{ 
          marginBottom: '20px', 
          padding: '16px',
          background: '#fafafa',
          borderRadius: '12px',
          display: 'flex', 
          alignItems: 'center', 
          gap: '12px', 
          flexWrap: 'wrap' 
        }}>
          <span style={{ fontWeight: '500', color: '#666', fontSize: '14px' }}>日期筛选：</span>
          <RangePicker
            value={dateRange}
            onChange={setDateRange}
            placeholder={['开始日期', '结束日期']}
            style={{ 
              width: '280px',
              borderRadius: '8px'
            }}
            format="YYYY-MM-DD"
          />
          <div style={{ display: 'flex', gap: '8px' }}>
            <Button 
              size="small" 
              onClick={() => handleQuickDateSelect(7)}
              type={dateRange && dayjs().diff(dateRange[0], 'day') === 7 ? 'primary' : 'default'}
              style={{ borderRadius: '6px' }}
            >
              过去一周
            </Button>
            <Button 
              size="small" 
              onClick={() => handleQuickDateSelect(30)}
              type={dateRange && dayjs().diff(dateRange[0], 'day') === 30 ? 'primary' : 'default'}
              style={{ borderRadius: '6px' }}
            >
              1个月
            </Button>
            <Button 
              size="small" 
              onClick={() => handleQuickDateSelect(90)}
              type={dateRange && dayjs().diff(dateRange[0], 'day') === 90 ? 'primary' : 'default'}
              style={{ borderRadius: '6px' }}
            >
              3个月
            </Button>
            <Button 
              size="small" 
              onClick={clearDateFilter}
              style={{ borderRadius: '6px' }}
            >
              清除
            </Button>
          </div>
        </div>

        <BaseTable
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          pagination={{
            current: currentPage,
            pageSize: pageSize,
            total: filteredData.length,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            }
          }}
          loading={loading}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
            getCheckboxProps: (record) => ({
              disabled: record.status === 'deleted'
            })
          }}
        />
      </Card>

      {/* 编辑/添加菜品模态框 */}
      <Modal
        title={editingItem ? '编辑菜品' : '添加菜品'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => {
          setModalVisible(false);
          setEditingItem(null);
          form.resetFields();
        }}
        confirmLoading={loading}
        width={800}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: '20px' }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="菜品名称"
                rules={[{ required: true, message: '请输入菜品名称' }]}
              >
                <Input placeholder="请输入菜品名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="分类"
                rules={[{ required: true, message: '请选择分类' }]}
              >
                <Select placeholder="请选择分类">
                  {categories.map(cat => (
                    <Option key={cat.value} value={cat.value}>{cat.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="price"
                label="售价"
                rules={[{ required: true, message: '请输入售价' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入售价"
                  min={0}
                  precision={2}
                  addonBefore="¥"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="originalPrice"
                label="原价"
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入原价"
                  min={0}
                  precision={2}
                  addonBefore="¥"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="stock"
                label="库存"
                rules={[{ required: true, message: '请输入库存' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入库存"
                  min={0}
                />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入菜品描述' }]}
          >
            <TextArea rows={3} placeholder="请输入菜品描述" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="available">可售</Option>
                  <Option value="unavailable">缺货</Option>
                  <Option value="hidden">隐藏</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="isHot"
                label="热门菜品"
                valuePropName="checked"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="isNew"
                label="新品推荐"
                valuePropName="checked"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="image"
            label="菜品图片"
          >
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>点击上传</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>

      {/* 图片预览 */}
      <Modal
        open={previewVisible}
        title="图片预览"
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="preview" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default MenuPage;